package org.bronycorps.mlptss.domain.model;

import java.util.ArrayList;
import java.util.List;

import org.bronycorps.mlptss.domain.model.event.StateChangeEvent;
import org.bronycorps.mlptss.domain.model.event.StateChangeEventListener;
import org.bronycorps.mlptss.manager.preferences.AssetsConfiguration;
import org.bronycorps.mlptss.manager.preferences.GameConfiguration;
import org.bronycorps.mlptss.utils.AnimationCache;
import org.bronycorps.mlptss.utils.DrawableAnimation;

public class SpecialMissile extends AbstractActorModel {

	public enum State {
		CREATION(0), EXPLODE(2), NORMAL(1);

		public final static State getStateByValue(int value) {
			for (State st : State.values()) {
				if (st.value == value) {
					return st;
				}
			}
			throw new EnumConstantNotPresentException(State.class, "State "
					+ value);
		}

		public final int value;

		private State(int value) {
			this.value = value;
		}

	}

	private int missileType = 1;

	private final Player owner;

	private State state = State.CREATION;

	private List<StateChangeEventListener> stateChangeListeners = new ArrayList<StateChangeEventListener>();

	public SpecialMissile(Player owner) {
		super();
		this.owner = owner;
	}

	public boolean addListener(StateChangeEventListener listener) {
		return this.stateChangeListeners.add(listener);
	}

	public void explode() {
		setState(State.EXPLODE);
	}

	public synchronized void fireStateChangeEvent() {
		for (StateChangeEventListener listener : this.stateChangeListeners) {
			listener.onStateChange(new StateChangeEvent(this));
		}
	}

	public DrawableAnimation getDefaultAnimation() {
		return AnimationCache.getInstance().get(
				this.owner.getCharacter().getSpecialMissileTypePrefix()
						+ this.missileType);
	}

	public DrawableAnimation getExplodeAnimation() {
		AssetsConfiguration config = GameConfiguration.getInstance()
				.getCurrentMod().getAssetsConfiguration();

		return AnimationCache.getInstance().get(
				config.getCommonExplosionAnimationName());
	}

	@Override
	public int getLife() {
		return 1;
	}

	public int getMissileType() {
		return this.missileType;
	}

	public Player getOwner() {
		return this.owner;
	}

	public State getState() {
		return this.state;
	}

	public boolean remove(Object listener) {
		return this.stateChangeListeners.remove(listener);
	}

	public void setMissileType(int missileType) {
		this.missileType = missileType;
	}

	public void setState(State state) {
		this.state = state;
		fireStateChangeEvent();
	}

}
